package com.rf.richfitwheel.outbill.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rf.richfitwheel.admin.sys.model.OrgVO;
import com.rf.richfitwheel.admin.sys.model.User;
import com.rf.richfitwheel.admin.sys.vo.UserVO;
import com.rf.richfitwheel.admin.utils.UserUtil;
import com.rf.richfitwheel.common.enums.ResultStatus;
import com.rf.richfitwheel.common.exception.BusinessException;
import com.rf.richfitwheel.common.exception.ResultException;
import com.rf.richfitwheel.common.utils.R;
import com.rf.richfitwheel.common.utils.StringUtils;
import com.rf.richfitwheel.common.utils.UuidUtil;
import com.rf.richfitwheel.outbill.dao.AcceptBillInfoMapper;
import com.rf.richfitwheel.outbill.feignclient.FSysUserService;
import com.rf.richfitwheel.outbill.feignclient.FWfTaskService;
import com.rf.richfitwheel.outbill.model.AcceptBillInfo;
import com.rf.richfitwheel.outbill.model.OutBillInfo;
import com.rf.richfitwheel.outbill.dao.OutBillInfoMapper;
import com.rf.richfitwheel.outbill.model.ReceiptBillInfo;
import com.rf.richfitwheel.outbill.rabbitmq.WorkflowModelCode;
import com.rf.richfitwheel.outbill.service.OutBillInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rf.richfitwheel.utils.OrgVoUtils;
import com.rf.richfitwheel.utils.PageJson;
import com.rf.richfitwheel.workflow.conf.WorkflowContants;
import com.rf.richfitwheel.workflow.entity.WfTaskParam;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author admin
 * @since 2024-06-11
 */
@Service
public class OutBillInfoServiceImpl extends ServiceImpl<OutBillInfoMapper, OutBillInfo> implements OutBillInfoService {

    @Autowired
    private OutBillInfoMapper outBillInfoMapper;

    @Autowired
    private AcceptBillInfoMapper acceptBillInfoMapper;

    //申请流程 控制服务
    @Autowired
    private FWfTaskService fWfTaskService;

    @Autowired
    private FSysUserService fSysUserService;

    @Autowired
    private OrgVoUtils orgVoUtils;

    @Override
    public PageJson pageJson(OutBillInfo outBillInfo) {
        Page<OutBillInfo> page = new Page<>(outBillInfo.getPageNum(), outBillInfo.getPageSize());
        QueryWrapper<OutBillInfo> queryWrapper = new QueryWrapper<>();
        //票据类型
        if (StringUtils.isNotBlank(outBillInfo.getOutBillType())) {
            queryWrapper.eq("out_bill_type", outBillInfo.getOutBillType());
        }
        //收款全称
        if (StringUtils.isNotBlank(outBillInfo.getReceiptBillFullname())) {
            queryWrapper.like("receipt_bill_fullname", outBillInfo.getReceiptBillFullname());
        }
        //票据金额
        if (outBillInfo.getAmtList().size() == 2 && (outBillInfo.getAmtList().get(0) != null)) {
            queryWrapper.between("bill_amount", outBillInfo.getAmtList().get(0), outBillInfo.getAmtList().get(1));
        }

        //出票日期
        if (StringUtils.isNotBlank(outBillInfo.getDateList())) {
            if (outBillInfo.getDateList().size() == 2 && (!outBillInfo.getDateList().get(0).isEmpty())) {
                queryWrapper.between("out_bill_start", DateUtil.parse(outBillInfo.getDateList().get(0), "yyyy-MM-dd"),
                        DateUtil.parse(outBillInfo.getDateList().get(1), "yyyy-MM-dd"));
            }
        }
        //单据状态
        if (StringUtils.isNotBlank(outBillInfo.getApvst())) {
            queryWrapper.eq("apvst", outBillInfo.getApvst());
        }
        //指令状态
        if (StringUtils.isNotBlank(outBillInfo.getInstructionStatus())) {
            queryWrapper.eq("instruction_status", outBillInfo.getInstructionStatus());
        }
        UserVO user = UserUtil.getUser();
        queryWrapper.eq("unitNumber", orgVoUtils.getParentOrgAndGrandpa(user).getParentOrg().getOrgCode());
        queryWrapper.orderByDesc("update_time");
        Page<OutBillInfo> pageData = outBillInfoMapper.selectPage(page, queryWrapper);
        return PageJson.of(pageData);
    }

    @Override
    public Boolean addFlow(Map<String, Object> params) {
        //1.人工登記
        UserVO user = UserUtil.getUser();
        OutBillInfo outBillInfo = JSONUtil.toBean(JSONUtil.parseObj(params.get("outBillInfo")), OutBillInfo.class);
        outBillInfo.setDataSource("1");
        outBillInfo.setApvst("2");
        outBillInfo.setCreateName(user.getStaffName());
        outBillInfo.setUpdateName(user.getStaffName());

        if (StringUtils.isNotBlank(outBillInfo.getId())) {
            outBillInfoMapper.updateById(outBillInfo);
        } else {
            outBillInfoMapper.insert(outBillInfo);
        }
        WfTaskParam wfTaskParam = (WfTaskParam) JSONObject.toBean(JSONObject.fromObject(params.get("wfTaskParam")), WfTaskParam.class);
        wfTaskParam.setUserVO(user);
        wfTaskParam.setProcessInsName(user.getDefaultOrg().getParentOrg().getOrgName() + "出票登记");
        wfTaskParam.setBusinessKey(outBillInfo.getId());//业务主键
        wfTaskParam.setApproveNo(outBillInfo.getOutBillNumber());//审批编号
        Map<String, Object> variables = wfTaskParam.getBaseParam(user);//组装流程参数
        variables.put("userId", user.getId());
        variables.put("userStaffName", user.getStaffName());
        variables.put("userOrgCode", user.getDefaultOrg().getOrgCode());
        wfTaskParam.setVariables(variables);
        R r = fWfTaskService.submitTask(wfTaskParam);
        if (!"0".equals(r.get("code").toString())) {
            throw new BusinessException(r.get("msg").toString());
        }
        return true;
    }

    @Override
    public Boolean modifyFlow(Map<String, Object> params, UserVO user) {
        OutBillInfo outBillInfo = JSONUtil.toBean(JSONUtil.parseObj(params.get("outBillInfo")), OutBillInfo.class);
        if (outBillInfo.getId() == null || "".equals(outBillInfo.getId())) {
            throw new ResultException(ResultStatus.FAILURE, "获取id失败，id不能为空！");
        }
        outBillInfo.setUpdateName(user.getStaffName());
        outBillInfoMapper.updateById(outBillInfo);
        WfTaskParam wfTaskParam = (WfTaskParam) JSONObject.toBean(JSONObject.fromObject(params.get("wfTaskParam")), WfTaskParam.class);
        Map<String, Object> variables = wfTaskParam.getVariables();//组装流程参数
        wfTaskParam.setVariables(variables);
        wfTaskParam.setUserVO(user);
        wfTaskParam.setProcessInsName("出票登记审批人审批");
        fWfTaskService.submitTask(wfTaskParam);
        return true;
    }

    @Override
    public void updateOutBill(String id, String status, String processInstanceId, Map<String, Object> variables) {
        QueryWrapper<OutBillInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        OutBillInfo outBillInfo = outBillInfoMapper.selectOne(queryWrapper);
        if (status.equals(WorkflowContants.PROCESS_STATUS_1)) {
            outBillInfo.setProcessInstanceId(processInstanceId);
            outBillInfo.setApvst("3");
            outBillInfoMapper.updateById(outBillInfo);
        }
        //这里判断是否是开票登记的流程结束
        if (status.equals(WorkflowContants.PROCESS_STATUS_2)) {
            //4本部审批结束
            outBillInfo.setApvst("4");
            outBillInfoMapper.updateById(outBillInfo);

            //生成提示承兑
            AcceptBillInfo acceptBillInfo = new AcceptBillInfo();
            BeanUtils.copyProperties(outBillInfo, acceptBillInfo, "id", "processInstanceId");
            acceptBillInfo.setApvst("2");
            acceptBillInfoMapper.insert(acceptBillInfo);

            //二联动自动发起提示承兑流程
            if ("2".equals(acceptBillInfo.getBusinessType()) || "3".equals(acceptBillInfo.getBusinessType())) {
                WfTaskParam wfTaskParam = new WfTaskParam();
/*                System.out.println(variables);
                UserVO user=new UserVO();
                user.setId(variables.get("userId").toString());
                OrgVO orgVO = new OrgVO();
                orgVO.setOrgCode(variables.get("userOrgCode").toString());
                user.setDefaultOrg(orgVO);
                user.setStaffName(variables.get("userStaffName").toString());*/
                User user = fSysUserService.getUserOnly(variables.get("userId").toString());
                UserVO userVO = new UserVO();
                BeanUtils.copyProperties(user, userVO);
                OrgVO orgVO = new OrgVO();
                orgVO.setOrgCode(variables.get("userOrgCode").toString());
                userVO.setDefaultOrg(orgVO);
                wfTaskParam.setUserVO(userVO);
                wfTaskParam.setBusinessKey(acceptBillInfo.getId());//业务主键
                wfTaskParam.setApproveNo(acceptBillInfo.getOutBillNumber());//审批编号
                wfTaskParam.setModuleType("bill");
                wfTaskParam.setQueueName("workflow.bill");
                wfTaskParam.setSkipFirstTask(true);
                wfTaskParam.setFinishProcess("n");
                // wfTaskParam.setSubmitToPrev("y");
                wfTaskParam.setProcessCode(WorkflowModelCode.OUT_BILL_BILL102);
                wfTaskParam.setOrgCode(variables.get("userOrgCode").toString());
                wfTaskParam.setProcessInsName("提示承兑联动提交");
                Map<String, Object> variables1 = wfTaskParam.getBaseParam(userVO);//组装流程参数
                variables1.put("userId", user.getId());
                variables1.put("userStaffName", user.getStaffName());
                variables1.put("userOrgCode", userVO.getDefaultOrg().getOrgCode());
                wfTaskParam.setVariables(variables1);
                R r = fWfTaskService.submitTask(wfTaskParam);
                if (!"0".equals(r.get("code").toString())) {
                    throw new BusinessException(r.get("msg").toString());
                }
            }
        }
        if (status.equals(WorkflowContants.PROCESS_STATUS_3)) {
            outBillInfo.setApvst("6");
            outBillInfoMapper.updateById(outBillInfo);
        }
    }

    @Override
    public boolean backFlow(Map<String, Object> params) {
        //1.人工登記
        UserVO user = UserUtil.getUser();
        OutBillInfo outBillInfo = JSONUtil.toBean(JSONUtil.parseObj(params.get("outBillInfo")), OutBillInfo.class);
        outBillInfo.setApvst("2");
        outBillInfo.setCreateName(user.getStaffName());
        outBillInfo.setUpdateName(user.getStaffName());
        outBillInfo.setIsBack("1");
        outBillInfo.setPreviousInstanceId(outBillInfo.getProcessInstanceId());
        if (StringUtils.isNotBlank(outBillInfo.getId())) {
            outBillInfoMapper.updateById(outBillInfo);
        } else {
            outBillInfoMapper.insert(outBillInfo);
        }
        WfTaskParam wfTaskParam = (WfTaskParam) JSONObject.toBean(JSONObject.fromObject(params.get("wfTaskParam")), WfTaskParam.class);
        wfTaskParam.setUserVO(user);
        wfTaskParam.setProcessInsName(user.getDefaultOrg().getParentOrg().getOrgName() + "出票登记撤销");
        wfTaskParam.setBusinessKey(outBillInfo.getId());//业务主键
        wfTaskParam.setApproveNo(outBillInfo.getOutBillNumber());//审批编号
        Map<String, Object> variables = wfTaskParam.getBaseParam(user);//组装流程参数
        wfTaskParam.setVariables(variables);
        R r = fWfTaskService.submitTask(wfTaskParam);
        if (!"0".equals(r.get("code").toString())) {
            throw new BusinessException(r.get("msg").toString());
        }
        return true;
    }

    @Override
    public boolean backModifyFlow(Map<String, Object> params, UserVO user) {
        OutBillInfo outBillInfo = JSONUtil.toBean(JSONUtil.parseObj(params.get("outBillInfo")), OutBillInfo.class);
        if (outBillInfo.getId() == null || "".equals(outBillInfo.getId())) {
            throw new ResultException(ResultStatus.FAILURE, "获取id失败，id不能为空！");
        }
        outBillInfo.setUpdateName(user.getStaffName());
        outBillInfoMapper.updateById(outBillInfo);
        WfTaskParam wfTaskParam = (WfTaskParam) JSONObject.toBean(JSONObject.fromObject(params.get("wfTaskParam")), WfTaskParam.class);
        Map<String, Object> variables = wfTaskParam.getVariables();//组装流程参数
        wfTaskParam.setVariables(variables);
        wfTaskParam.setUserVO(user);
        wfTaskParam.setProcessInsName("撤销出票登记审批人审批");
        fWfTaskService.submitTask(wfTaskParam);
        return true;
    }

    @Override
    public void backAcceptBill(String id, String status, String processInstanceId) {
        QueryWrapper<OutBillInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        OutBillInfo outBillInfo = outBillInfoMapper.selectOne(queryWrapper);
        if (status.equals(WorkflowContants.PROCESS_STATUS_1)) {
            outBillInfo.setProcessInstanceId(processInstanceId);
            outBillInfo.setApvst("3");
            outBillInfo.setState("0");
            outBillInfoMapper.updateById(outBillInfo);
        }
        //这里判断是否是开票登记的流程结束
        if (status.equals(WorkflowContants.PROCESS_STATUS_2)) {
            //4本部审批结束
            outBillInfo.setApvst("4");
            outBillInfo.setState("1");
            outBillInfoMapper.updateById(outBillInfo);

        }
        if (status.equals(WorkflowContants.PROCESS_STATUS_3)) {
            outBillInfo.setApvst("2");
            outBillInfo.setIsBack("0");
            outBillInfo.setState("1");
            outBillInfoMapper.updateById(outBillInfo);
        }
    }

}
